package com.xumt.hwHMSdemo.HMSserver;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.huawei.agconnect.config.AGConnectServicesConfig;
import com.huawei.agconnect.exception.AGCException;
import com.huawei.hmf.tasks.OnCompleteListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.aaid.HmsInstanceId;
import com.huawei.hms.common.ApiException;
import com.huawei.hms.push.HmsMessageService;
import com.huawei.hms.push.HmsMessaging;

public class MyPushService extends HmsMessageService {
    private static final String TAG = "DemoHmsMessageService";


    @Override
    public void onNewToken(String token) {
        Log.i(TAG, "received refresh token:" + token);
        // send the token to your app server.
        if (!TextUtils.isEmpty(token)) {
            // This method callback must be completed in 10 seconds. Otherwise, you need to start a new Job for callback processing.
            refreshedTokenToServer(token);
        }
    }

    @Override
    public void onNewToken(String token, Bundle bundle) {
        Log.i(TAG, "recive refresh token:" + token);
    }

    public void refreshedTokenToServer(String token) {
        Log.i(TAG, "sending token to server. token:" + token);
    }

    public static void getToken(final Context context) {
        new Thread() {
            @Override
            public void run() {
                try {//从json读取appID
                    String appId = AGConnectServicesConfig.fromContext(context).getString("client/app_id");
                    String tokenScope = "HCM";//token标识HCM
                    String token = HmsInstanceId.getInstance(context).getToken(appId, tokenScope);
                    Log.i(TAG, "get Token:" + token);
                    if (!TextUtils.isEmpty(token)) {//判断token为空？
                        sendRegTokenToServer(token);
                    }
                } catch (ApiException e) {
                    Log.e(TAG, "get token failed" + e);
                }
            }
        }.start();
    }

    private static void sendRegTokenToServer(String token) {
        Log.i(TAG, "sending token to server. token:" + token);
    }

    //订阅功能
    public static void subscribe(Context context, final String topic) {
        try {//主题订阅
            HmsMessaging.getInstance(context).subscribe(topic).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(Task<Void> task) {
                    //获取订阅结果
                    if (task.isSuccessful()) {
                        Log.i(TAG, topic + "订阅成功");
                    } else {
                        Log.e(TAG, topic + "订阅失败" + task.getException().getMessage());
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG,topic+"订阅失败"+e.getMessage());
        }
    }
}
